package com.zyong.encryption.client;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;

import com.zyong.encryption.common.netty.bean.Content;
import com.zyong.encryption.client.config.NettyConfig;
import com.zyong.encryption.common.netty.bean.HeartBeat;
import com.zyong.encryption.client.helper.SpringBeanUtils;
import com.zyong.encryption.client.netty.NettyClientService;
import com.zyong.encryption.common.enums.NettyMessageActionEnum;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.zyong.encryption.client.netty.handler.NettyClientMessageHandler;

/**
 * 
 * @author xiaoyu
 */
@SpringBootApplication
public class EncryptionClientApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(EncryptionClientApplication.class);
    
    public static void main(String[] args) {
        final ConfigurableApplicationContext applicationContext = SpringApplication.run(EncryptionClientApplication.class, args);
        SpringBeanUtils.getInstance().setCfgContext(applicationContext);
        
        final NettyClientService nettyClientService = applicationContext.getBean(NettyClientService.class);
        final NettyConfig nettyConfig = applicationContext.getBean(NettyConfig.class);
        nettyClientService.start(nettyConfig);
        
        try {
            Thread.sleep(20 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        NettyClientMessageHandler nettyClientMessageHandler = applicationContext.getBean(NettyClientMessageHandler.class);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        
        LOGGER.info("Netty Start Time: {}", new Date());
        for (int i = 0; i < 1000000; i++) {
            final int num = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    execute(nettyClientMessageHandler, num);
                }
            });
        }
        executorService.shutdown();
        LOGGER.info("Netty End Time: {}", new Date());
    }
    
    private static void execute(NettyClientMessageHandler nettyClientMessageHandler, int num) {
        HeartBeat heartBeat = new HeartBeat();
        heartBeat.setAction(NettyMessageActionEnum.ENCRYPT.getCode());
        Content content = new Content();
        content.setOriginContent("zyong" + num);
        heartBeat.setContent(content);
        
        Object object = nettyClientMessageHandler.sendNettyMessage(heartBeat);
        LOGGER.info("{} Encryption Result: {}", content.getOriginContent(), object);
    }
}
